<template>
	<view>
		<!-- <cu-custom :isBack="true" style="z-index: 1000;">
			<block slot="backText">{{sensorName}}</block>
		</cu-custom> -->
		<view id="dataModel" style="background-color: #FFFFFF;">
			<view class="flex text-center">
				<view class="flex-sub" @tap="tapRealTimeChart">
					<view class="padding text-df">{{$t('realTime')}}</view>
					<view class="margin-bottom-xs" v-if="showModel == 'realTimeChart'"
						style="width:100%;height:2rpx;background-color: #4b4b4b;">
					</view>
				</view>
				<view class="flex-sub" @tap="tapHistorical()">
					<view class="padding text-df">{{$t('history')}}</view>
					<view class="margin-bottom-xs" v-if="showModel == 'history'"
						style="width:100%;height:2rpx;background-color: #4b4b4b;"></view>
				</view>
			</view>
			<view class="flex justify-center align-center" style="height: 60rpx;">
				<picker mode="date" :value="startDate " :end="formatDate(initEndTimestamp)" @change='startDateChange'>
					<view class="text-grey text-df">{{startDate}}</view>
				</picker>
				<view class="margin-left-lg margin-right-lg text-center" style="width: 25%;">
					<text class="text-df">{{$t('to')}}</text>
				</view>
				<picker mode="date" :end="formatDate(initEndTimestamp)" @change='endDateChange'>
					<view class="text-grey text-df">{{endDate}}</view>
				</picker>
			</view>
		</view>

		<view :style="{'top':modelHeight + 'px','height':screenHeight - modelHeight + 'px'}" class="bg-white">
			<view v-for="(item,index) in chartList" :key="index" v-show="!showSettingModal && !showErrorModal"
				class="bg-white">
				<view class="action margin-bottom-sm flex justify-between margin-left-sm">
					<view>
						<text class="cuIcon-titles text-green"></text>
						<text class="text-bold margin-right-sm">
							<text v-if="item.remark && item.remark!==''">
								{{item.remark}}
							</text>
							<text v-else>
								{{item.name}}
							</text>
						</text>
					</view>
				</view>
				<view class="margin-bottom">
					<line height="500rpx" v-if="item.showType === 'echarts'" :dataList="item.dataList" />
					<view style="height: 500rpx;overflow-y: auto;margin-left: 40rpx;margin-right: 40rpx;" v-else
						class="cu-list menu sm-bordercard-menu">
						<view class="cu-item" v-for="(val,valIndex) in item.dataList" :key="valIndex">
							<view class="content">
								{{val.val}}
							</view>
							<view class="action">
								{{val.time}}
							</view>
						</view>
					</view>
				</view>

			</view>
			<view>
				<view class="cu-bar margin-top bg-white">
					<view class="action">
						<text class="cuIcon-title text-blue"></text>{{$t('enable')+$t('script')}}
					</view>
					<view class="action">
						<switch :class="[themeConfig.theme,enableEval?'checked':'']" :checked="enableEval"
							@change="changeEnableEval"></switch>
					</view>
				</view>
				<view class="cu-bar margin-top bg-white">
					<view class="action">
						<text class="cuIcon-title text-blue"></text>{{$t('filter')+$t('repeat')}}
					</view>
					<view class="action">
						<switch :class="[themeConfig.theme,filterRepeat?'checked':'']" :checked="filterRepeat"
							@change="changeFilterRepeat">
						</switch>
					</view>
				</view>
				<view class="cu-bar margin-top bg-white">
					<view class="action">
						<text class="cuIcon-title text-blue"></text>{{$t('show')+$t('hidden')}}
					</view>
					<view class="action">
						<switch :class="[themeConfig.theme,showHidden?'checked':'']" :checked="showHidden"
							@change="changeShowHidden"></switch>
					</view>
				</view>
				<view class="cu-bar margin-top bg-white">
					<view class="action">
						<text class="cuIcon-title text-blue"></text>{{$t('add')+$t('frame')}}
					</view>
					<view class="action">
						<switch :class="[themeConfig.theme,addFrame?'checked':'']" :checked="addFrame"
							@change="changeAddFrame"></switch>
					</view>
				</view>
			</view>
			<view style="width: 100%;height: 200rpx;"></view>
		</view>

		<!-- #ifndef APP -->
		<picker v-if="showModel == 'history'" :range="timeList" value="timeIndex" @change='timeChange'
			range-key="label">
			<cover-view class="cu-avatar round lg light bg-white" :style="{backgroundColor:themeConfig.primaryColor}"
				style="position:fixed;right:20rpx;bottom: 260rpx;z-index: 1000;">
				<cover-text class="text-df text-white">{{$t('time')}}</cover-text>
			</cover-view>
		</picker>

		<view v-else-if="getDateInfo.keyName">
			<cover-view @tap="getDate()" class="cu-avatar round lg light bg-white"
				:style="{backgroundColor:themeConfig.primaryColor}"
				style="position:fixed;right:20rpx;bottom: 260rpx;z-index: 1000;">
				<cover-text class="text-df text-white">{{$t('refresh')}}</cover-text>
			</cover-view>
		</view>

		<view>
			<cover-view @tap="showSettingModal = true" class="cu-avatar round lg light bg-white"
				:style="{backgroundColor:themeConfig.primaryColor}"
				style="position:fixed;right:20rpx;bottom: 140rpx;z-index: 1000;">
				<cover-text class="text-df text-white">{{$t('command')}}</cover-text>
			</cover-view>
		</view>
		<!-- #endif -->



		<view class="cu-modal drawer-modal justify-start" :class="showSettingModal ? 'show' : ''"
			@tap="showSettingModal = false">
			<view class="cu-dialog basis-lg" @tap.stop="" style="flex-basis: 80%;padding: 10rpx;overflow-y: auto;">
				<setting :deviceCore="deviceCore" :deviceName="deviceName" :showGoToSensor="false">
				</setting>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="showErrorModal?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideErrorModal">{{$t('close')}}</view>
				</view>
				<view class="padding-xl">
					{{settingError}}
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		showToast,
		showLoading,
		hideLoading
	} from '@/util/toast.js'
	import myConfig from '@/myConfig.js'
	import * as deviceSettingApi from '@/api/iot/iotDeviceSettingApi.js'
	import {
		formatDateTime,
		formatDate
	} from '@/util/formatTime.js'
	import * as deviceSensorApi from '@/api/iot/iotDeviceSensorApi.js'
	import Line from '@/components/UniChars/Line.vue'
	import Setting from '@/components/ztn-custom/Setting/index.vue'
	import {
		listenWebSocket,
		leaveWebSocket
	} from '@/util/websocketUtil.js'
	import {
		listTime
	} from '@/util/dataUtil.js'
	import * as storage from '@/util/storage.js'
	import {
		nextTick
	} from 'vue'
	export default {
		data() {
			return {
				showModel: 'history',
				isShowFilter: true,
				chartList: [],
				explainList: [],
				startTimestamp: '',
				endTimestamp: '',
				initEndTimestamp: '',
				initStartTimestamp: '',
				startDate: '',
				endDate: '',
				endcreatedTime: '',
				interval: null,
				modelHeight: 0,
				deviceCore: null,
				deviceName: null,
				sensorName: null,
				enableEval: storage.getEnableEval(),
				addFrame: storage.getAddFrame(),
				filterRepeat: storage.getFilterRepeat(),
				showSettingModal: false,
				showHidden: storage.getShowHidden(),
				getDateInfo: {},
				settingError: '',
				showErrorModal: false,
				screenHeight: storage.getScreenHeight(),
				wsMonitor: {
					room: 'iot:device:' + this.deviceCore,
					onmessage: this.onSocketMsg
				},
				timeList: []
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		onUnload(e) {
			this.unBindSocket()
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: this.$store.state.themeConfig.commonColor, //前景颜色值，包括按钮、标题、状态栏的颜色，仅支持 #ffffff 和 #000000
				backgroundColor: this.$store.state.themeConfig.primaryColor, //背景颜色值，有效值为十六进制颜色
			})
		},
		onLoad(option) {
			this.initOption = option
			this.init(option)
			this.bindSocket()
		},
		onShow() {
			const that = this
			nextTick(() => {
				uni.createSelectorQuery().select('#dataModel').boundingClientRect((e) => {
					that.modelHeight = e.height - 0.5
				}).exec()
			})
			this.init(this.initOption)
		},
		methods: {
			hideErrorModal() {
				this.showErrorModal = false
			},
			getDate() {
				showLoading(this.$t('loading'), true)
				deviceSettingApi.sendSetting({
					deviceCore: this.deviceCore,
					value: this.getDateInfo.value,
					keyName: this.getDateInfo.keyName,
					port: this.getDateInfo.port
				}).then((res) => {
					if (res.data) {
						showToast(this.$t('success'), 'none', 1000, true)
					} else {
						this.showErrorModal = true,
							this.settingError = res.msg
					}
					hideLoading()
				})
			},
			getSensorList() {
				deviceSensorApi.getListWith({
					deviceCore: this.deviceCore,
					withExplain: false,
					withParam: false,
					withSetting: true,
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						data.forEach(sensor => {
							if (sensor.settingList) {
								sensor.settingList.forEach(setting => {
									if (setting.keyName === 'getData') {
										if (setting.port === this.port || !this.getDateInfo
											.show) {
											this.getDateInfo = {
												show: true,
												...setting
											}
										}
									}
								})
							}
						})
					}
				})
			},
			deviceSetting() {
				this.showSettingModal = true
			},
			changeEnableEval(e) {
				this.enableEval = e.detail.value
				storage.setEnableEval(this.enableEval)
				this.tapHistorical()
			},
			changeFilterRepeat(e) {
				this.filterRepeat = e.detail.value
				storage.setFilterRepeat(this.filterRepeat)
				this.tapHistorical()
			},
			changeShowHidden(e) {
				this.showHidden = e.detail.value
				storage.setShowHidden(this.showHidden)
				this.tapHistorical()
			},
			changeAddFrame(e) {
				this.addFrame = e.detail.value
				storage.setAddFrame(this.addFrame)
				this.tapHistorical()
			},
			bindSocket() {
				this.wsMonitor.room = 'iot:device:' + this.deviceCore
				listenWebSocket(this.wsMonitor)
			},
			unBindSocket() {
				leaveWebSocket(this.wsMonitor)
				clearInterval(this.interval)
				this.interval = null
			},
			onSocketMsg(nowData) {
				// if (this.showModel !== 'realTimeChart') {
				// 	return
				// }
				if (nowData.type == 'deviceData') {
					const data = JSON.parse(nowData.msg);
					if (data.deviceUpload) {
						if (data.deviceUpload.sensorList && data.deviceUpload.sensorList.length > 0) {
							data.deviceUpload.sensorList.forEach(sensor => {
								if (sensor.port === this.port) {
									if (sensor.explainList && sensor.explainList.length > 0) {
										for (let i = 0; i < this.chartList.length; i++) {
											const canvas = this.chartList[i]
											if (canvas.showType === 'echarts') {
												let have = false
												sensor.explainList.forEach(explain => {
													if (explain.keyName === canvas.keyName) {
														if (canvas.dataList.length >= 60) {
															canvas.dataList.splice(0, 1)
														}

														canvas.dataList.push({
															time: this.formaterTime(data
																.deviceUpload
																.timestamp),
															val: explain.value
														})
														canvas.lastValue = canvas.value
														canvas.lastRawValue = canvas.lastValue
														canvas.value = explain.value
														canvas.rawValue = explain.rawValue
														canvas.valueDate = this.formaterTime(data
															.deviceUpload.timestamp)
														have = true
													}
												})
												if (!have && this.addFrame && this.filterRepeat) {
													if (canvas.dataList.length >= 60) {
														canvas.dataList.splice(0, 1)
													}
													canvas.dataList.push({
														time: this.formaterTime(data.deviceUpload
															.timestamp),
														val: this.enableEval ? canvas.value : canvas
															.rawValue
													})
												}
											} else {

											}

										}
									}
								}
							})
						}
					}
				}
			},
			init(option) {
				this.deviceName = option.deviceName
				this.deviceCore = option.deviceCore
				this.sensorId = option.sensorId
				this.sensorName = option.sensorName
				this.port = option.port
				this.tapHistorical()
				this.getSensorList()
				const language = storage.getLanguage()
				this.timeList = listTime(this)
			},
			tapRealTimeChart() {
				this.showModel = 'realTimeChart'
				for (let i = 0; i < this.chartList.length; i++) {
					const canvas = this.chartList[i]
					canvas.dataList = [canvas.dataList[canvas.dataList.length - 1]]
				}
			},
			tapHistorical() {
				this.showModel = 'history'
				this.getCurrentDate()
				this.getListWithExplain()
			},
			formatDate(timestamp) {
				return formatDate(timestamp)
			},
			getCurrentDate() {
				const time = new Date()
				this.startTimestamp = time.setTime(time.getTime() / 1000 - 7 * 24 * 60 * 60).toString();
				this.endTimestamp = Math.round(new Date().getTime() / 1000).toString();
				this.startDate = this.formatDate(this.startTimestamp)
				this.endDate = this.formatDate(this.endTimestamp)
				this.initStartTimestamp = this.startTimestamp
				this.initEndTimestamp = this.endTimestamp
			},
			getListWithExplain() {
				showLoading(this.$t('loading'), true)
				this.chartList = []
				deviceSensorApi.getHistoryListWithExplain({
					enableEval: this.enableEval,
					filterRepeat: this.filterRepeat,
					addFrame: this.addFrame,
					sensorId: this.sensorId,
					startTime: this.startTimestamp,
					endTime: this.endTimestamp,
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						const chartList = []
						let createdTime = 0
						this.explainList = data.explainList
						for (let i = 0, j = this.explainList.length; i < j; i++) {
							const explain = this.explainList[i]
							if (!this.showHidden && explain.hidden) {
								continue
							}
							const explainLastValueMap = {}
							const dataList = []
							let valMap
							for (let n = 0, m = data.dataList.length; n < m; n++) {
								const dataItem = data.dataList[n]
								valMap = dataItem.val
								if (valMap[explain.keyName] != undefined) {
									explainLastValueMap[explain.keyName] = valMap[explain.keyName]
									dataList.push({
										time: this.formaterTime(dataItem.createdTime),
										val: explainLastValueMap[explain.keyName],
									});
								} else if (this.addFrame && this.filterRepeat && explainLastValueMap[explain
										.keyName]) {
									dataList.push({
										time: this.formaterTime(dataItem.createdTime),
										val: explainLastValueMap[explain.keyName],
									});
								}
							}

							const item = {
								...explain
							}
							item.dataList = dataList;
							if (item.dataList.length === 0) {
								item.dataList = [{
									time: this.formaterTime(explain.valueDate),
									val: explain.value,
								}]
							}
							if (this.enableEval && (explain.type === 'line' || explain.type === 'number')) {
								item.showType = 'echarts'
							} else {
								item.showType = 'string'
							}
							chartList.push(item)
						}
						this.chartList = chartList
						this.endcreatedTime = createdTime
					}
					hideLoading()
				})
			},
			formaterTime(createdTime) {
				const newDate = new Date();
				newDate.setTime(createdTime * 1000);
				return (newDate.getMonth() + 1) + '/' + newDate.getDate() + ' ' + newDate
					.getHours() + ':' + newDate.getMinutes()
			},
			startDateChange(e) {
				const date = e.detail.value.replace(/-/g, '/')
				const timestamp = (new Date(date).getTime() / 1000).toString();
				const endTimestamp = this.endTimestamp
				if (endTimestamp < timestamp || endTimestamp == timestamp) {
					showToast(this.$t('lessEndDateTip'), 'none', 1000, false) //请选择小于结束日期
				} else {
					this.startDate = e.detail.value
					this.startTimestamp = timestamp
					this.getListWithExplain()
				}
			},
			endDateChange(e) {
				const date = e.detail.value.replace(/-/g, '/');
				const timestamp = (new Date(date).getTime() / 1000 + 1 * 24 * 60 * 60).toString();
				const startTimestamp = this.startTimestamp
				if (startTimestamp > timestamp || startTimestamp == timestamp) {
					showToast(this.$t('greaterStartDateTip'), 'none', 1000, false) //请选择大于开始日期
				} else {
					this.endDate = e.detail.value
					this.endTimestamp = timestamp
					this.getListWithExplain()
				}
			},
			timeChange(e) {
				this.chartData = []
				const index = parseInt(e.detail.value)
				const endcreatedTime = this.endcreatedTime
				this.startTimestamp = (parseInt(endcreatedTime) - this.timeList[index].value).toString()
				this.getListWithExplain()

			}
		},
		components: {
			Line,
			Setting
		},
		onShareAppMessage(res) {
			const nickName = storage.getNickName()
			return {
				title: `${nickName}${this.$t('share')}${this.deviceName}`,
				path: `/pages/deviceSensorData/deviceSensorData?deviceName=${this.deviceName}&deviceCore=${this.deviceCore}&sensorId=
${this.sensorId}&sensorName=${this.sensorName}`,
				success: (res) => {
					// console.log(res)
				}
			}
		}
	}
</script>

<style>

</style>
